package com.test.mybatis.executor;

import com.test.mybatis.config.Configuration;
import com.test.mybatis.config.MappedStatement;
import com.test.mybatis.util.ReflectUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{

    private final Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    public <E> List<E> query(MappedStatement mappedStatement, Object parameter) {

        List<E> resultList = new ArrayList<>();
        try {
            Connection connection = DriverManager.getConnection(configuration.getJdbcUrl(), configuration.getJdbcUsername(), configuration.getJdbcPassword());
            Statement statement = connection.createStatement();
            // 执行查询操作，将结果存储在ResultSet对象中
            String query = mappedStatement.getSql();

            ResultSet resultSet = statement.executeQuery(query);

            Class<?> resultTypeClass = Class.forName(mappedStatement.getResultType());
            // 遍历结果集并处理数据
            while (resultSet.next()) {
                E result = (E) resultTypeClass.getConstructor(null).newInstance();
                //把从数据库查询出来的结果集字段的数据要设置到result
                ReflectUtil.setProToBeanFromResult(result, resultSet);
                resultList.add(result);
            }
            // 关闭连接、Statement和ResultSet
            resultSet.close();
            statement.close();
            connection.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
}
